from tools import config
import os , re , subprocess , base64 , binascii
from PySide6.QtGui import QGuiApplication

def binwalk分离(self):
    # config.清理输出(self)
    self.ui.print_echo.append("正在运行binwalk分离")
    try:
        输出 = subprocess.check_output(f"python -m binwalk -e {config.file_name} -C {config.文件目录}")
        for i in 输出.decode().split('\r\n'): self.ui.print_echo.append(i)
        self.ui.print_echo.append(f"分离成功，请到{config.文件目录}目录下查看分离结果")
    except ModuleNotFoundError as e:
        self.ui.print_echo.append(f"binwalk错误： {e}")
    except:
        self.ui.print_echo.append("没装binwalk吧,或者没配置环境?")
    config.清理目录(self)
   
def format文件分离(self):
    self.ui.print_echo.append("正在运行foremost分离")
    try: 
        subprocess.check_output(f"./tools/jiaoben/foremost.exe -v -o {config.文件目录+'foremost分离结果'} -i {config.file_name} ")
        with open(config.文件目录+'foremost分离结果/audit.txt','r') as f:
            for i in f.readlines(): 
                i = i.split('\n')[0]
                if i != '': 
                    self.ui.print_echo.append(i.split('\n')[0])
        self.ui.print_echo.append(f"分离成功，请到{config.文件目录+'foremost分离结果'}目录下查看分离结果")
    except:
        self.ui.print_echo.append("foremost分离错误,请检查是否已存在foremost文件夹")
    config.清理目录(self)

def 字符串搜索(self):
    # config.清理输出(self)
    file_data = config.文件读取(self)
    设置正则 = self.ui.set_str1.text()
    if 设置正则 != '':
        正则参数 = []
        正则参数.append(设置正则+"{.*}")
        正则参数.append(base64.b64encode(设置正则.encode()).decode()[0:4]+"[a-zA-Z0-9=]+")
        正则参数.append("[0-9a-fA-F]+"+binascii.hexlify(设置正则.encode()).decode()[1:]+"[0-9a-fA-F]+")
        正则参数.append('&#[0-9].+;')
        self.ui.print_echo.append(f"正则表达式已设置为 : {'、'.join(正则参数)}")
        QGuiApplication.processEvents()
    else:
        正则参数 = ['flag.*','flag{.*}','Zmxh','[\u4e00-\u9fa5]+','&#[0-9].+;','[0-9a-fA-F]+66c6167[0-9a-fA-F]+']
        self.ui.print_echo.append(f"要搜索的字符串.默认为 {' , '.join(正则参数)}")
        QGuiApplication.processEvents()
    try:
        for i in 正则参数:  # 列表中内容循环存进 i
            s = re.findall(f"{i}",file_data.decode(),re.I)  
            if s:
                for x in s:
                    self.输出信号.emit("匹配到:" + x)
            else:
                pass
        self.ui.print_echo.append("正则匹配完成")
    except:
        self.ui.print_echo.append("搜索错误,请重新设置flag")
    config.清理目录(self)

def 字频分析(self):
    # # config.清理输出(self)
    self.ui.print_echo.append('正在运行字频分析')
    try:
        file_data = config.文件读取(self)
        字频 = {}
        lines = file_data.decode().replace('\n', '').replace('\r', '')
        self.设置进度.emit(len(lines))
        x=0
        for line in lines:
            if 字频.get(line) == None :
                字频.update({line: 1}) 
            else:
                字频[line]+=1
            x+=1
            self.进度信号.emit(x)
        字频排序=sorted(字频.items(),  key=lambda d: d[1], reverse=True)
    except:
        self.输出信号.emit('字频分析错误')
    for i in 字频排序:
        self.输出信号.emit("字频排序为:"+str(i))
    config.清理目录(self)

def 可打印字符(self):
    # # config.清理输出(self)
    file_data = config.文件读取(self)
    try:
        chars = r"A-Za-z0-9/\-:.,_$%'()[\]<> "
        shortestReturnChar = 4
        regExp = '[%s]{%d,}' % (chars, shortestReturnChar)
        pattern = re.compile(regExp)
        字符 = []
        data = pattern.findall(file_data.decode("utf-8", "ignore"))
        for i in data:
            字符.append(i)
        if not 字符:
            self.ui.print_echo.append('无可打印字符')
        else:
            self.ui.print_echo.append(''.join(字符))
    except:
        self.ui.print_echo.append('出现错误')
    config.清理目录(self)

def 零宽字符隐写(self):
    # # config.清理输出(self)
    self.ui.print_echo.append('正在调用网页进行零宽字符隐写解密')
    os.startfile(os.path.relpath('./tools/jiaoben/unicode_steganography.html'))
    '''  # ! 这部分代码是打算调用js直接进行解码,但是还没做出来,一直测试不过去
    with open("C:/Users/SQM/Desktop/新建文件夹/1.txt",'rb') as f:
        file_data = f.read() 
    print(file_data.decode('UTF-8-sig'))
    with open("./tools/jiaoben/unicode_steganography.js",'r', encoding='utf8') as js_file:
        jscode = js_file.read()
        js = js2py.EvalJs()
    js.execute(jscode)
    r1 = js.function(file_data.decode('UTF-8-sig'))
    '''
    config.清理目录(self)

def 字符串翻转(self):
    # # config.清理输出(self)
    file_data = config.文件读取(self).decode()
    self.输出信号.emit(file_data[::-1])
    config.清理目录(self)

def 日志分析(self):  # TODO 待完成
    # # config.清理输出(self)
    web关键词=['system','passthru','shell_exec','exec','popen','proc_open',
         'eval','assert','call_user_func','base64_decode','gzinflate','gzunconmpress',
         'gzdecode','srt_rot13','requiere','require_once','include_once','file_get_contents','file_put_contents','fputs','fwrite',
         'SetHandler','auto_prepend_file','auto_append_file']
    config.清理目录(self)
